// packageA/pages/tools/pomodoro/pomodoro.js
Page({
  data: {
    // 计时器状态
    isRunning: false,
    isPaused: false,
    currentMode: 'work', // work, shortBreak, longBreak
    
    // 时间设置（分钟）
    workTime: 25,
    shortBreakTime: 5,
    longBreakTime: 15,
    
    // 当前时间显示
    currentTime: 25 * 60, // 秒
    displayTime: '25:00',
    
    // 番茄周期
    pomodoroCount: 0,
    totalPomodoros: 0,
    
    // 进度
    progress: 0,
    
    // 设置模式
    showSettings: false,
    
    // 计时器ID
    timer: null
  },

  onLoad() {
    this.loadSettings()
    this.initCurrentTime()
  },

  onUnload() {
    this.stopTimer()
  },

  onHide() {
    // 页面隐藏时保存状态
    this.saveTimerState()
  },

  onShow() {
    // 页面显示时恢复状态
    this.restoreTimerState()
  },

  // 加载设置
  loadSettings() {
    const settings = wx.getStorageSync('pomodoroSettings') || {}
    const workTime = settings.workTime || 25
    const shortBreakTime = settings.shortBreakTime || 5
    const longBreakTime = settings.longBreakTime || 15
    
    this.setData({
      workTime,
      shortBreakTime,
      longBreakTime
    })
  },

  // 初始化当前时间
  initCurrentTime() {
    const { currentMode, workTime, shortBreakTime, longBreakTime } = this.data
    let time
    
    switch(currentMode) {
      case 'work':
        time = workTime * 60
        break
      case 'shortBreak':
        time = shortBreakTime * 60
        break
      case 'longBreak':
        time = longBreakTime * 60
        break
    }
    
    this.setData({
      currentTime: time,
      displayTime: this.formatTime(time),
      progress: 0
    })
  },

  // 开始/暂停计时器
  toggleTimer() {
    if (this.data.isRunning) {
      this.pauseTimer()
    } else {
      this.startTimer()
    }
  },

  // 开始计时器
  startTimer() {
    this.setData({
      isRunning: true,
      isPaused: false
    })
    
    this.data.timer = setInterval(() => {
      this.tick()
    }, 1000)
    
    // 播放开始音效
    this.playSound('start')
  },

  // 暂停计时器
  pauseTimer() {
    this.setData({
      isRunning: false,
      isPaused: true
    })
    
    this.stopTimer()
    
    // 播放暂停音效
    this.playSound('pause')
  },

  // 停止计时器
  stopTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.data.timer = null
    }
  },

  // 重置计时器
  resetTimer() {
    this.stopTimer()
    this.setData({
      isRunning: false,
      isPaused: false
    })
    this.initCurrentTime()
    
    // 清除保存的状态
    wx.removeStorageSync('pomodoroTimerState')
  },

  // 计时器滴答
  tick() {
    let { currentTime, currentMode, workTime, shortBreakTime, longBreakTime } = this.data
    
    if (currentTime <= 0) {
      this.timerComplete()
      return
    }
    
    currentTime--
    
    // 计算进度
    let totalTime
    switch(currentMode) {
      case 'work':
        totalTime = workTime * 60
        break
      case 'shortBreak':
        totalTime = shortBreakTime * 60
        break
      case 'longBreak':
        totalTime = longBreakTime * 60
        break
    }
    
    const progress = ((totalTime - currentTime) / totalTime) * 100
    
    this.setData({
      currentTime,
      displayTime: this.formatTime(currentTime),
      progress
    })
  },

  // 计时器完成
  timerComplete() {
    this.stopTimer()
    this.setData({
      isRunning: false,
      isPaused: false,
      progress: 100
    })
    
    const { currentMode, pomodoroCount } = this.data
    
    if (currentMode === 'work') {
      // 工作时间结束，增加番茄数
      const newPomodoroCount = pomodoroCount + 1
      const newTotalPomodoros = this.data.totalPomodoros + 1
      
      this.setData({
        pomodoroCount: newPomodoroCount,
        totalPomodoros: newTotalPomodoros
      })
      
      // 保存总番茄数到本地
      wx.setStorageSync('totalPomodoros', newTotalPomodoros)
      
      // 决定下一个模式
      if (newPomodoroCount % 4 === 0) {
        this.switchMode('longBreak')
      } else {
        this.switchMode('shortBreak')
      }
    } else {
      // 休息时间结束，回到工作模式
      this.switchMode('work')
    }
    
    // 播放完成音效和震动
    this.playSound('complete')
    wx.vibrateShort({
      type: 'heavy'
    })
    
    // 显示完成提示
    this.showCompleteMessage()
  },

  // 切换模式
  switchMode(mode) {
    this.setData({
      currentMode: mode
    })
    this.initCurrentTime()
  },

  // 显示完成消息
  showCompleteMessage() {
    const { currentMode } = this.data
    let title, content
    
    if (currentMode === 'work') {
      title = '🍅 番茄时间结束！'
      content = '恭喜完成一个番茄时钟！是时候休息一下了。'
    } else {
      title = '☕ 休息时间结束！'
      content = '休息时间结束，准备开始下一个番茄时钟吧！'
    }
    
    wx.showModal({
      title,
      content,
      showCancel: false,
      confirmText: '好的',
      success: () => {
        // 自动开始下一阶段
        // this.startTimer()
      }
    })
  },

  // 显示设置
  showSettings() {
    this.setData({
      showSettings: true
    })
  },

  // 隐藏设置
  hideSettings() {
    this.setData({
      showSettings: false
    })
  },

  // 保存设置
  saveSettings() {
    const { workTime, shortBreakTime, longBreakTime } = this.data
    
    wx.setStorageSync('pomodoroSettings', {
      workTime,
      shortBreakTime,
      longBreakTime
    })
    
    this.hideSettings()
    this.resetTimer()
    
    wx.showToast({
      title: '设置已保存',
      icon: 'success'
    })
  },

  // 调整时间设置
  adjustTime(e) {
    const { type, action } = e.currentTarget.dataset
    const { workTime, shortBreakTime, longBreakTime } = this.data
    
    let newTime
    switch(type) {
      case 'work':
        newTime = action === 'increase' ? workTime + 5 : Math.max(5, workTime - 5)
        this.setData({ workTime: newTime })
        break
      case 'shortBreak':
        newTime = action === 'increase' ? shortBreakTime + 1 : Math.max(1, shortBreakTime - 1)
        this.setData({ shortBreakTime: newTime })
        break
      case 'longBreak':
        newTime = action === 'increase' ? longBreakTime + 5 : Math.max(5, longBreakTime - 5)
        this.setData({ longBreakTime: newTime })
        break
    }
  },

  // 格式化时间显示
  formatTime(seconds) {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
  },

  // 播放音效
  playSound(type) {
    // 使用震动代替音效
    switch(type) {
      case 'start':
        wx.vibrateShort({ type: 'light' })
        break
      case 'pause':
        wx.vibrateShort({ type: 'medium' })
        break
      case 'complete':
        wx.vibrateShort({ type: 'heavy' })
        break
    }
  },

  // 保存计时器状态
  saveTimerState() {
    if (this.data.isRunning || this.data.isPaused) {
      wx.setStorageSync('pomodoroTimerState', {
        isRunning: this.data.isRunning,
        isPaused: this.data.isPaused,
        currentMode: this.data.currentMode,
        currentTime: this.data.currentTime,
        pomodoroCount: this.data.pomodoroCount,
        timestamp: Date.now()
      })
    }
  },

  // 恢复计时器状态
  restoreTimerState() {
    const state = wx.getStorageSync('pomodoroTimerState')
    if (state) {
      const timeDiff = Math.floor((Date.now() - state.timestamp) / 1000)
      let currentTime = state.currentTime
      
      if (state.isRunning) {
        currentTime = Math.max(0, currentTime - timeDiff)
      }
      
      this.setData({
        isRunning: state.isRunning && currentTime > 0,
        isPaused: state.isPaused && currentTime > 0,
        currentMode: state.currentMode,
        currentTime,
        displayTime: this.formatTime(currentTime),
        pomodoroCount: state.pomodoroCount
      })
      
      if (this.data.isRunning && currentTime > 0) {
        this.startTimer()
      } else if (currentTime <= 0) {
        this.resetTimer()
      }
    }
    
    // 加载总番茄数
    const totalPomodoros = wx.getStorageSync('totalPomodoros') || 0
    this.setData({ totalPomodoros })
  }
})